<template>
  <div class="tooling-ledger-container">
    <!-- 搜索 -->
    <div v-show="showSearchForm" class="search-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="方案编号">
          <el-input v-model="formInline.PlanNo" placeholder="请输入方案编号" clearable />
        </el-form-item>
        <el-form-item label="方案名称">
          <el-input v-model="formInline.PlanName" placeholder="请输入方案名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTableData">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="table-wrapper">
      <div class="table-operations">
        <el-button type="primary" plain @click="onAdd">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button type="success" plain :disabled="selectedRows.length!==1" @click="onEditSelected">
          <el-icon><Edit /></el-icon> 修改
        </el-button>
        <el-button type="danger" plain :disabled="selectedRows.length==0" @click="onBatchDelete">
          <el-icon><Delete /></el-icon> 删除
        </el-button>
      </div>
      <div class="table-header-actions">
        <el-button
          circle
          size="large"
          @click="showSearchForm = !showSearchForm"
          :title="showSearchForm ? '收起查询' : '展开查询'"
        >
          <el-icon><Search /></el-icon>
        </el-button>
        <el-button
          circle
          size="large"
          @click="getTableData()"
          title="刷新"
        >
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
      <el-table :data="tableData" border style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="55" align="center" header-align="center" />
        <el-table-column prop="planNo" label="方案编号" align="center" header-align="center" />
        <el-table-column prop="planName" label="方案名称" align="center" header-align="center" />
        <el-table-column prop="businessType" label="业务类型" align="center" header-align="center" />
        <el-table-column prop="isEnabled" label="是否启用" align="center" header-align="center">
          <template #default="scope">
            {{ scope.row.isEnabled == 0 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" header-align="center">
          <template #default="scope">
            <el-button link type="primary" plain size="small" @click="onEditRow(scope.row)">
              <el-icon><Edit /></el-icon> 修改
            </el-button>
            <el-button link type="danger" plain size="small" @click="onDeleteRow(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager-wrapper">
        <el-pagination
          v-model:current-page="page.PageIndex"
          v-model:page-size="page.pageSize"
          :page-sizes="[10, 15, 20, 25,30]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog :title="dialogTitle" :model-value="dialogVisible" width="800px" @close="onDialogClose" @update:model-value="onDialogVisible">
      <el-form :model="dialogForm" ref="dialogFormRef" label-width="100px" :rules="rules">
        <el-form-item label="方案编号" prop="planNo" required>
          <el-input v-model="dialogForm.planNo" placeholder="请输入方案编号" :disabled="dialogMode==='edit'||autoGenDisabled" style="width: 300px;" />
          <el-switch
            v-if="dialogMode==='add'"
            v-model="autoGenChecked"
            :disabled="autoGenDisabled"
            active-text="自动生成"
            style="margin-left:10px"
            @change="onAutoGenSwitch"
          />
        </el-form-item>
        <el-form-item label="方案名称" prop="planName" required>
          <el-input v-model="dialogForm.planName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessTypeArr">
          <el-checkbox-group v-model="dialogForm.businessTypeArr">
            <el-checkbox v-for="item in businessTypeOptions" :key="item.value" :label="item.value">{{item.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-radio-group v-model="dialogForm.isEnabled" style="display:inline-flex;align-items:center;gap:0;">
            <el-radio :label="0" style="margin-right: 10px;">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="dialogForm.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- 检测项/物料产品子表区域 -->
        <div v-if="dialogMode==='edit'" style="margin-bottom:10px;">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="检测项" name="item">
              <div style="margin-bottom:10px;display:flex;align-items:center;gap:10px;">
                <el-button type="primary" plain size="small" @click="onAddItem">
                  <el-icon><Plus /></el-icon> 新增
                </el-button>
                <el-button type="success" plain size="small" :disabled="selectedItemRows.length!==1" @click="onEditItem">
                  <el-icon><Edit /></el-icon> 修改
                </el-button>
                <el-button type="danger" plain size="small" :disabled="selectedItemRows.length===0" @click="onBatchDeleteItem">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
              <el-table 
                class="item-table"
                :data="itemTableData" 
                border 
                style="width:100%"
                @selection-change="onItemSelectionChange"
                :fit="true"
                :resizable="false"
              >
                <el-table-column type="selection" width="55" align="center" header-align="center" />
                <el-table-column prop="inspection_item" label="检测项名称" min-width="120" show-overflow-tooltip align="center" header-align="center" />
                <el-table-column prop="inspection_tool" label="检测工具" min-width="120" show-overflow-tooltip align="center" header-align="center" />
                <el-table-column prop="inspection_requirement" label="检测要求" min-width="120" show-overflow-tooltip align="center" header-align="center" />
                <el-table-column prop="standard_value" label="标准值" min-width="90" align="center" header-align="center" />
                <el-table-column prop="unit" label="单位" min-width="80" align="center" header-align="center" />
                <el-table-column prop="upper_tolerance" label="误差上限" min-width="90" align="center" header-align="center" />
                <el-table-column prop="lower_tolerance" label="误差下限" min-width="90" align="center" header-align="center" />
                <el-table-column prop="diagram" label="说明图" min-width="120" show-overflow-tooltip align="center" header-align="center" />
                <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip align="center" header-align="center" />
                <el-table-column label="操作" width="180" fixed="right" align="center" header-align="center">
                  <template #default="scope">
                    <el-button 
                      link 
                      type="primary" 
                      size="small" 
                      @click="onEditItem(scope.row)"
                    >
                      <el-icon><Edit /></el-icon> 修改
                    </el-button>
                    <el-button 
                      link 
                      type="danger" 
                      size="small" 
                      @click="onDeleteItem(scope.row)"
                    >
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                v-model:current-page="itemPage.PageIndex"
                v-model:page-size="itemPage.pageSize"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="itemPage.total"
                style="margin-top:0;justify-content:flex-end"
                @size-change="onItemSizeChange"
                @current-change="onItemCurrentChange"
              />
            </el-tab-pane>
            <el-tab-pane label="物料产品" name="product">
              <div style="margin-bottom:10px;display:flex;align-items:center;">
                <el-button type="primary" plain @click="onAddProduct">
                  <el-icon><Plus /></el-icon> 新增
                </el-button>
                <el-button type="success" plain :disabled="selectedProductRows.length!==1" @click="onEditProductSelected">
                  <el-icon><Edit /></el-icon> 修改
                </el-button>
                <el-button type="danger" plain :disabled="selectedProductRows.length===0" @click="onBatchDeleteProduct">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
              <el-table :data="productTableData" border class="product-table" style="width:100%" @selection-change="onProductSelectionChange">
                <el-table-column type="selection" width="40" align="center" header-align="center" />
                <el-table-column prop="material_code" label="产品物料编码" width="130" align="center" header-align="center" />
                <el-table-column prop="material_name" label="产品物料名称" width="130" align="center" header-align="center" />
                <el-table-column prop="specification" label="规格型号" width="120" align="center" header-align="center" />
                <el-table-column prop="min_inspection_quantity" label="最低检测数" width="110" align="center" header-align="center" />
                <el-table-column prop="unit" label="单位" align="center" header-align="center" />
                <el-table-column prop="max_defective_quantity" label="最大不合格数" width="90" align="center" header-align="center" />
                <el-table-column prop="max_critical_defect" label="最大致命缺陷率" width="90" align="center" header-align="center" />
                <el-table-column prop="max_major_defect" label="最大严重缺陷率" width="90" align="center" header-align="center" />
                <el-table-column prop="max_minor_defect" label="最大轻微缺陷率" width="90" align="center" header-align="center" />
                <el-table-column label="操作" width="140" align="center" header-align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="onEditProduct(scope.row)">
                      <el-icon><Edit /></el-icon> 修改
                    </el-button>
                    <el-button link type="danger" @click="onDeleteProduct(scope.row)">
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                v-model:current-page="productPage.PageIndex"
                v-model:page-size="productPage.pageSize"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="productPage.total"
                style="margin-top:10px;"
                @size-change="onProductSizeChange"
                @current-change="onProductCurrentChange"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- 检测项/物料产品新增/编辑对话框 -->
        <el-dialog :title="itemDialogTitle" v-model="itemDialogVisible" width="1200px" class="product-dialog">
          <el-form :model="itemDialogForm" ref="itemDialogFormRef" label-width="120px">
            <template v-if="activeTab==='product'">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="产品物料编码" prop="productCode" required>
                    <el-input v-model="itemDialogForm.productCode" placeholder="请输入产品物料编码">
                      <template #append>
                        <el-button :icon="Search" @click="openProductSelectDialog" />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="产品物料名称" prop="productName">
                    <el-input v-model="itemDialogForm.productName" placeholder="请输入产品物料名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="规格型号" prop="spec">
                    <el-input v-model="itemDialogForm.spec" placeholder="请输入规格型号" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="最低检测数" prop="minCount">
                    <el-input-number v-model="itemDialogForm.minCount" :min="1" style="width: 100%;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="最大不合格数" prop="maxUnqualified">
                    <el-input-number v-model="itemDialogForm.maxUnqualified" :min="0" style="width: 100%;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单位" prop="unit">
                    <el-input v-model="itemDialogForm.unit" placeholder="请输入单位" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="最大致命缺陷率" prop="maxFatal">
                    <el-input-number v-model="itemDialogForm.maxFatal" :min="0" style="width: 100%;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="最大严重缺陷率" prop="maxSerious">
                    <el-input-number v-model="itemDialogForm.maxSerious" :min="0" style="width: 100%;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="最大轻微缺陷率" prop="maxSlight">
                    <el-input-number v-model="itemDialogForm.maxSlight" :min="0" :max="100" style="width: 100%;" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="itemDialogForm.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item label="检测项" prop="inspection_item" required>
                <el-input
                  v-model="itemDialogForm.inspection_item"
                  placeholder="请选择检测项"
                  style="width: 220px;"
                  readonly
                />
                <el-button style="margin-left: 8px;" @click="openItemSelectDialog" :icon="Search" circle />
              </el-form-item>
              <el-form-item label="检测工具" prop="inspection_tool">
                <el-input v-model="itemDialogForm.inspection_tool" placeholder="请输入检测工具" />
              </el-form-item>
              <el-form-item label="检测要求" prop="inspection_requirement">
                <el-input v-model="itemDialogForm.inspection_requirement" type="textarea" placeholder="请输入内容" />
              </el-form-item>
              <el-form-item label="标准值" prop="standard_value">
                <el-input-number v-model="itemDialogForm.standard_value" :min="0" />
              </el-form-item>
              <el-form-item label="单位" prop="unit">
                <el-select v-model="itemDialogForm.unit" placeholder="请选择单位" style="width: 220px;">
                  <el-option v-for="item in unitOptions" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item label="误差上限" prop="upper_tolerance">
                <el-input-number v-model="itemDialogForm.upper_tolerance" :min="0" />
              </el-form-item>
              <el-form-item label="误差下限" prop="lower_tolerance">
                <el-input-number v-model="itemDialogForm.lower_tolerance" :min="0" />
              </el-form-item>
              <el-form-item label="说明图" prop="diagram">
                <el-input v-model="itemDialogForm.diagram" placeholder="请输入说明图" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="itemDialogForm.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </template>
          </el-form>
          <template #footer>
            <el-button @click="itemDialogVisible=false">取消</el-button>
            <el-button type="primary" @click="onItemDialogSubmit">确定</el-button>
          </template>
        </el-dialog>
      </el-form>
      <template #footer>
        <el-button @click="onDialogClose">取消</el-button>
        <el-button type="primary" @click="onDialogSubmit">确定</el-button>
      </template>
    </el-dialog>
    <!-- 检测项选择对话框 -->
    <el-dialog
      title="物料产品选择"
      v-model="itemSelectDialogVisible"
      width="1200px"
      top="5vh"
      class="centered-dialog-title"
    >
      <div class="item-select-header-row">
        <div class="item-select-type-group">
          <span class="item-select-type-label">检测项类型</span>
          <el-button
            v-for="type in itemTypeOptions"
            :key="type"
            size="small"
            :type="activeItemType === type ? 'primary' : 'default'"
            @click="handleItemTypeClick(type)"
          >{{ type }}</el-button>
        </div>
        <div class="item-select-name-group">
          <span class="item-select-name-label">检测项名称</span>
          <el-input placeholder="请输入检测项名称" style="width:200px;" />
        </div>
      </div>
      <div class="item-select-btn-row">
        <el-button type="primary"><i class="el-icon-search" />搜索</el-button>
        <el-button><i class="el-icon-refresh" />重置</el-button>
      </div>
      <div style="max-height:60vh;overflow-y:auto;">
        <el-table :data="itemSelectTableData" style="width: 100%;" @row-click="handleRadioChange">
          <el-table-column label="" width="40">
            <template #default="scope">
              <el-radio
                v-model="itemSelectRadio"
                :label="scope.row.itemCode"
                @change="handleRadioChangeWithEvent(scope.row, $event)"
              >
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="itemCode" label="检测项编码" min-width="120" />
          <el-table-column prop="itemName" label="检测项名称" min-width="120" />
          <el-table-column prop="itemType" label="检测项类型" min-width="100" />
          <el-table-column prop="tool" label="检测工具" min-width="120" />
        </el-table>
      </div>
      <el-pagination
        v-model:current-page="itemSelectPage.PageIndex"
        v-model:page-size="itemSelectPage.pageSize"
        :total="itemSelectPage.total"
        :page-sizes="[10]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px;"
        @current-change="handleItemSelectPageChange"
      />
      <template #footer>
        <el-button @click="itemSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onItemSelectConfirm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog
      title="产品物料选择"
      v-model="productSelectDialogVisible"
      width="800px"
      top="10vh"
    >
      <div>这里是产品物料选择内容（待实现）</div>
      <template #footer>
        <el-button @click="productSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onProductSelectConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue'
import http from '@/api/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'

const showSearchForm = ref(true)

const formInline = reactive({
  PlanNo: '',
  PlanName: '',
})
const page = reactive({
  PageIndex: 1,
  pageSize: 10,
  total: 0
})
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])
const dialogVisible = ref(false)
const dialogForm = ref<any>({})
const dialogFormRef = ref()
const dialogMode = ref<'add'|'edit'>('add')
const dialogTitle = ref('')
const businessTypeOptions = [
  { label: '来料检验', value: '1' },
  { label: '自制工序检验', value: '2' },
  { label: '首检', value: '3' },
  { label: '巡检', value: '4' },
  { label: '自检', value: '5' },
  { label: '成品检验', value: '6' },
  { label: '生产退料检验', value: '7' },
  { label: '销售退货检验', value: '8' },
  { label: '发货检验', value: '9' }
]
const autoGenDisabled = ref(false)
const autoGenChecked = ref(false)
const activeTab = ref('item')
const itemSearch = ref('')
const itemTableData = ref<any[]>([])
const itemPage = reactive({ PageIndex: 1, pageSize: 10, total: 0 })
const selectedItemRows = ref<any[]>([])
const itemDialogVisible = ref(false)
const itemDialogTitle = ref('')
const itemDialogForm = ref<any>({})
const itemDialogFormRef = ref()
const productTableData = ref<any[]>([])
const productPage = reactive({ PageIndex: 1, pageSize: 10, total: 0 })
const selectedProductRows = ref<any[]>([])
const itemSelectDialogVisible = ref(false)
const allItemSelectData = [
  // 第1页
  { itemCode: 'I0036', itemName: '宽度', itemType: '尺寸', tool: '' },
  { itemCode: 'I0038', itemName: '颜色是否纯正', itemType: '外观', tool: '' },
  { itemCode: 'I0040', itemName: '外观照片', itemType: '外观', tool: '' },
  { itemCode: 'I0041', itemName: '检测过程视频', itemType: '外观', tool: '' },
  { itemCode: 'I0042', itemName: '个数清点', itemType: '外观', tool: '' },
  { itemCode: 'I0043', itemName: '合格证编号', itemType: '外观', tool: '' },
  { itemCode: 'I0051', itemName: '螺丝刀', itemType: '尺寸', tool: '' },
  { itemCode: 'I0049', itemName: '螺丝刀39', itemType: '尺寸', tool: '' },
  { itemCode: 'I0050', itemName: '螺栓', itemType: '尺寸', tool: '' },
  { itemCode: '230629260119', itemName: '螺丝刀19', itemType: '尺寸', tool: '' },
  // 第2页
  { itemCode: '2222222', itemName: '就很烦好基友', itemType: '外观', tool: '' },
  { itemCode: '230629260104', itemName: '螺丝刀04', itemType: '尺寸', tool: '' },
  { itemCode: 'I0055', itemName: '是否漏电', itemType: '成分', tool: '电笔' },
  { itemCode: 'I0062', itemName: 'ces', itemType: '成型', tool: '1' },
  { itemCode: 'I0064', itemName: '厚度', itemType: '尺寸', tool: '红外线技术' },
  { itemCode: 'I0066', itemName: '吧', itemType: '粘检', tool: '' },
  { itemCode: '666', itemName: '333', itemType: '成型', tool: '' },
  { itemCode: 'lw042', itemName: '颜色', itemType: '外观', tool: '' },
  { itemCode: '123456', itemName: '金属涂料', itemType: '外观', tool: '视觉传感器' },
  // 第3页
  { itemCode: '21645', itemName: '111', itemType: '烧成', tool: '' },
  { itemCode: '10086', itemName: '鼠弟', itemType: '性能', tool: '老鼠夹' },
  { itemCode: '420', itemName: '长度n', itemType: '尺寸', tool: '' },
  { itemCode: '10043', itemName: '长', itemType: '尺寸', tool: '' },
  { itemCode: '111', itemName: 'admin', itemType: '外观', tool: '' },
  { itemCode: 'I0069', itemName: '叫驴子', itemType: '烧成', tool: '手' },
  { itemCode: 'Y23206', itemName: '外观', itemType: '外观', tool: '摄像头' },
  { itemCode: '12332', itemName: 'GGG', itemType: '外观', tool: '机器' },
  { itemCode: 'I0070', itemName: '111111', itemType: '烧成', tool: '222' },
  { itemCode: '04455', itemName: '焊接', itemType: '性能', tool: '机械臂' }
]
const itemSelectPage = reactive({ PageIndex: 1, pageSize: 10, total: allItemSelectData.length })
const itemSelectTableData = ref(allItemSelectData.slice(0, 10))
const selectedItemRow = ref<any>(null)
const unitOptions = [
  '微米1', '公支', '英支', '匹', '捆', '层', '套'
]
const itemTypeOptions = [
  '全部', '成型', '粘检', '烧成', '尺寸', '外观', '重量', '性能', '成分'
]
const activeItemType = ref('全部')
const itemSelectRadio = ref('')
const productSelectDialogVisible = ref(false)

const rules = reactive({
  planNo: [
    { required: true, message: '方案编号为必填项', trigger: 'blur' }
  ],
  planName: [
    { required: true, message: '方案名称为必填项', trigger: 'blur' }
  ]
})

const getTableData = () => {
  http.get('/api/PlanInfo/GetList/GetPlanInfo?PlanNo=' + formInline.PlanNo + '&PlanName=' + formInline.PlanName + '&PageIndex=' + page.PageIndex + '&pageSize=' + page.pageSize).then(res => {
    tableData.value = res.rows
    page.total = res.total
  })
}
const handleSizeChange = (val: number) => {
  page.pageSize = val
  getTableData()
  itemTableData.value = []
  itemPage.total = 0
}
const handleCurrentChange = (val: number) => {
  page.PageIndex = val
  getTableData()
  itemTableData.value = []
  itemPage.total = 0
}
const onSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}
const onAdd = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '添加质检方案'
  dialogForm.value = {
    planNo: '',
    auto: false,
    planName: '',
    businessTypeArr: [],
    isEnabled: 0,
    remarks: ''
  }
  autoGenDisabled.value = false
  autoGenChecked.value = false
  dialogVisible.value = true
}
const onEditSelected = () => {
  if (selectedRows.value.length !== 1) return
  const row = selectedRows.value[0]
  dialogMode.value = 'edit'
  dialogTitle.value = '修改质检方案'
  dialogForm.value = {
    planNo: row.planNo,
    auto: false,
    planName: row.planName,
    businessTypeArr: row.businessType ? row.businessType.split(',') : [],
    isEnabled: row.isEnabled,
    remarks: row.remarks || ''
  }
  formInline.PlanNo = row.planNo
  itemTableData.value = []
  itemPage.PageIndex = 1
  itemPage.pageSize = 10
  itemPage.total = 0
  getItemTableData()
  getProductTableData()
  dialogVisible.value = true
}
const onEditRow = (row: { planNo: string; planName: string; businessType?: string; isEnabled: number; remarks?: string }) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '修改质检方案'
  dialogForm.value = {
    planNo: row.planNo,
    auto: false,
    planName: row.planName,
    businessTypeArr: row.businessType ? row.businessType.split(',') : [],
    isEnabled: row.isEnabled,
    remarks: row.remarks || ''
  }
  formInline.PlanNo = row.planNo
  getItemTableData()
  getProductTableData()
  dialogVisible.value = true
}
const onDialogClose = () => {
  dialogVisible.value = false
  autoGenDisabled.value = false
  autoGenChecked.value = false
  itemTableData.value = []
  itemPage.PageIndex = 1
  itemPage.pageSize = 10
  itemPage.total = 0
}
const onDialogVisible = (val: boolean) => {
  dialogVisible.value = val
}
const onDialogSubmit = () => {
  dialogFormRef.value.validate?.().then(() => {
    const submitData: any = {
      planNo: dialogForm.value.planNo,
      planName: dialogForm.value.planName,
      businessType: dialogForm.value.businessTypeArr.join(','),
      isEnabled: dialogForm.value.isEnabled,
      remarks: dialogForm.value.remarks,
      items: itemTableData.value,
      products: productTableData.value
    }
    if (dialogMode.value === 'add') {
      http.post('/api/PlanInfo/Add/AddplanInfo', submitData).then(res => {
        ElMessage.success(res.message)
        dialogVisible.value = false
        getTableData()
      })
    } else {
      if (selectedRows.value.length && selectedRows.value[0].id) {
        submitData.id = selectedRows.value[0].id
      }
      http.post('/api/PlanInfo/Update/UpdateplanInfo', submitData).then(res => {
        ElMessage.success(res.message)
        dialogVisible.value = false
        getTableData()
      })
    }
  })
}
const onBatchDelete = async () => {
  if (selectedRows.value.length === 0) return
  ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗？`, '提示', {
    type: 'warning',
    cancelButtonText: '取消',
    confirmButtonText: '确认'
  })
    .then(async () => {
      let successCount = 0
      for (const row of selectedRows.value) {
        try {
          const res = await http.post('/api/PlanInfo/Delete/DeleteplanInfo', { id: row.id })
          if (res.status == 0 || res.status === 0) {
            successCount++
          }
        } catch (err) {
          // 忽略失败
        }
      }
      if (successCount > 0) ElMessage.success(`成功删除${successCount}条记录`)
      getTableData()
    })
}
const onDeleteRow = (row: any) => {
  ElMessageBox.confirm('确认删除该条记录吗？', '提示', {
    type: 'warning',
    cancelButtonText: '取消',
    confirmButtonText: '确认'
  })
    .then(() => {
      http.post('/api/PlanInfo/Delete/DeleteplanInfo', { id: row.id }).then(res => {
        ElMessage.success(res.message)
        getTableData()
      })
    })
}
const onReset = () => {
  formInline.PlanNo = ''
  formInline.PlanName = ''
  getTableData()
}
const generatePlanNo = () => {
  // 找到表格中最大的planNo
  let maxNo = ''
  tableData.value.forEach(row => {
    if (/^QCT\d{8}$/.test(row.planNo)) {
      if (row.planNo > maxNo) maxNo = row.planNo
    }
  })
  let baseDate: Date
  if (!maxNo) {
    baseDate = new Date()
  } else {
    const y = parseInt(maxNo.slice(3, 7))
    const m = parseInt(maxNo.slice(7, 9))
    const d = parseInt(maxNo.slice(9, 11))
    baseDate = new Date(y, m - 1, d)
    baseDate.setDate(baseDate.getDate() + 1)
  }
  const yyyy = baseDate.getFullYear()
  const mm = String(baseDate.getMonth() + 1).padStart(2, '0')
  const dd = String(baseDate.getDate()).padStart(2, '0')
  dialogForm.value.planNo = `QCT${yyyy}${mm}${dd}`
  autoGenDisabled.value = true
}
const onAutoGenSwitch = (val: boolean) => {
  if (val) {
    generatePlanNo()
    autoGenDisabled.value = true
  }
}
const onItemSelectionChange = (rows: any[]) => { selectedItemRows.value = rows }
const onItemSizeChange = (val: number) => {
  itemPage.pageSize = val
  itemPage.PageIndex = 1
  getItemTableData()
}
const onItemCurrentChange = (val: number) => {
  itemPage.PageIndex = val
  getItemTableData()
}
const onAddItem = () => {
  itemDialogTitle.value = '添加检测模板-检测项'
  itemDialogForm.value = {
    inspection_item: '',
    inspection_tool: '',
    inspection_requirement: '',
    standard_value: 0,
    unit: '',
    upper_tolerance: 0,
    lower_tolerance: 0,
    diagram: '',
    remark: ''
  }
  itemDialogVisible.value = true
}
const onEditItem = (row?: any) => {
  const editRow = row || selectedItemRows.value[0]
  if (!editRow) return
  itemDialogTitle.value = '修改检测模板-检测项'
  // 兼容旧数据结构
  itemDialogForm.value = {
    id: editRow.id,
    inspection_item: editRow.inspection_item || editRow.itemName || '',
    inspection_tool: editRow.inspection_tool || editRow.tool || '',
    inspection_requirement: editRow.inspection_requirement || editRow.requirement || '',
    standard_value: editRow.standard_value ?? editRow.standardValue ?? 0,
    unit: editRow.unit || '',
    upper_tolerance: editRow.upper_tolerance ?? editRow.upperLimit ?? 0,
    lower_tolerance: editRow.lower_tolerance ?? editRow.lowerLimit ?? 0,
    diagram: editRow.diagram || editRow.descImg || '',
    remark: editRow.remark || ''
  }
  itemDialogVisible.value = true
}
const onDeleteItem = (row: any) => {
  ElMessageBox.confirm('确认删除该检测项吗？', '提示', {
    type: 'warning',
    cancelButtonText: '取消',
    confirmButtonText: '确认'
  }).then(() => {
    http.post('/api/Testingitems/Delete/DelTestingitems', { id: row.id }).then(res => {
      ElMessage.success(res.message || '删除成功')
      getItemTableData()
    })
  })
}
const onBatchDeleteItem = () => {
  if (selectedItemRows.value.length === 0) return
  ElMessageBox.confirm(`确认删除选中的${selectedItemRows.value.length}条检测项吗？`, '提示', {
    type: 'warning',
    cancelButtonText: '取消',
    confirmButtonText: '确认'
  }).then(async () => {
    let successCount = 0
    for (const row of selectedItemRows.value) {
      try {
        const res = await http.post('/api/Testingitems/Delete/DelTestingitems', { id: row.id })
        if (res.status == 0 || res.status === 0) {
          successCount++
        }
      } catch (err) {
        // 忽略失败
      }
    }
    if (successCount > 0) ElMessage.success(`成功删除${successCount}条检测项`)
    getItemTableData()
    selectedItemRows.value = []
  })
}
const onProductSelectionChange = (rows: any[]) => { selectedProductRows.value = rows }
const onProductSizeChange = (val: number) => {
  productPage.pageSize = val
  productPage.PageIndex = 1
  getProductTableData()
}
const onProductCurrentChange = (val: number) => {
  productPage.PageIndex = val
  getProductTableData()
}
const onAddProduct = () => {
  itemDialogTitle.value = '添加检测模板-产品'
  itemDialogForm.value = {
    productCode: '', productName: '', spec: '', minCount: 1, maxUnqualified: 0, unit: '', maxFatal: 0, maxSerious: 0, maxSlight: 100, remark: ''
  }
  itemDialogVisible.value = true
}
const onEditProduct = (row?: any) => {
  const editRow = row || selectedProductRows.value[0]
  if (!editRow) return
  itemDialogTitle.value = '修改检测模板-产品'
  // 字段映射反填
  itemDialogForm.value = {
    productCode: editRow.material_code || '',
    productName: editRow.material_name || '',
    spec: editRow.specification || '',
    minCount: editRow.min_inspection_quantity ?? 1,
    maxUnqualified: editRow.max_defective_quantity ?? 0,
    unit: editRow.unit || '',
    maxFatal: editRow.max_critical_defect ?? 0,
    maxSerious: editRow.max_major_defect ?? 0,
    maxSlight: editRow.max_minor_defect ?? 100,
    remark: editRow.remark || ''
  }
  itemDialogVisible.value = true
}
const onDeleteProduct = (row: any) => {
  ElMessageBox.confirm('确认删除该产品吗？', '提示', {
    type: 'warning',
    cancelButtonText: '取消',
    confirmButtonText: '确认'
  }).then(() => {
    http.post('/api/ProductInspectionTemplate/DelProductInspectionTemplate', { id: row.id }).then(res => {
      ElMessage.success(res.message || '删除成功')
      getProductTableData()
    })
  })
}
const onBatchDeleteProduct = () => {
  if (selectedProductRows.value.length === 0) return
  ElMessageBox.confirm(`确认删除这${selectedProductRows.value.length}条数据吗？`, '提示', {
    type: 'warning',
    cancelButtonText: '取消',
    confirmButtonText: '确认'
  }).then(async () => {
    let successCount = 0
    for (const row of selectedProductRows.value) {
      try {
        const res = await http.post('/api/ProductInspectionTemplate/DelProductInspectionTemplate', { id: row.id })
        if (res.status == 0 || res.status === 0) {
          successCount++
        }
      } catch (err) {
        // 忽略失败
      }
    }
    if (successCount > 0) ElMessage.success('已成功删除这几条数据')
    getProductTableData()
    selectedProductRows.value = []
  })
}
const onItemDialogSubmit = () => {
  itemDialogFormRef.value.validate?.().then(() => {
    if (activeTab.value === 'item') {
      let newItem = { ...itemDialogForm.value }
      newItem.PlanNo = formInline.PlanNo
      if (itemDialogTitle.value.startsWith('添加')) {
        http.post('/api/Testingitems/Add/AddTestingitems', newItem).then((res: any) => {
          ElMessage.success(res.message)
          itemDialogVisible.value = false
          getItemTableData()
        })
      } else {
        // id优先从表单取，否则从选中行取
        if (!newItem.id && selectedItemRows.value[0] && selectedItemRows.value[0].id) {
          newItem.id = selectedItemRows.value[0].id
        }
        http.post('/api/Testingitems/Update/UpdateTestingitems', newItem).then(() => {
          itemDialogVisible.value = false
          getItemTableData()
        })
      }
    } else {
      // 产品模板相关
      let productData = {
        material_code: itemDialogForm.value.productCode,
        material_name: itemDialogForm.value.productName,
        planNo: formInline.PlanNo,
        specification: itemDialogForm.value.spec,
        min_inspection_quantity: itemDialogForm.value.minCount ?? 1,
        max_defective_quantity: itemDialogForm.value.maxUnqualified ?? 0,
        unit: itemDialogForm.value.unit,
        max_critical_defect: itemDialogForm.value.maxFatal ?? 0,
        max_major_defect: itemDialogForm.value.maxSerious ?? 0,
        max_minor_defect: itemDialogForm.value.maxSlight ?? 100,
        remark: itemDialogForm.value.remark
      }
      if (itemDialogTitle.value.startsWith('添加')) {
        http.post('/api/ProductInspectionTemplate/AddProductInspectionTemplate', productData).then((res: any) => {
          ElMessage.success(res.message)
          itemDialogVisible.value = false
          // 可根据需要刷新产品表格
        })
      } else {
        http.post('/api/ProductInspectionTemplate/UpdateProductInspectionTemplate', productData).then((res: any) => {
          ElMessage.success(res.message)
          itemDialogVisible.value = false
          // 可根据需要刷新产品表格
        })
      }
    }
  })
}
const openItemSelectDialog = () => {
  itemSelectDialogVisible.value = true
  itemSelectRadio.value = ''
  filterItemSelectData()
}
const onSelectItemRow = (row: any) => {
  selectedItemRow.value = row
}
const onItemSelectConfirm = () => {
  if (selectedItemRow.value) {
    itemDialogForm.value.inspection_item = selectedItemRow.value.itemName
  }
  itemSelectDialogVisible.value = false
}
const handleItemSelectPageChange = (val: number) => {
  itemSelectPage.PageIndex = val
  filterItemSelectData()
}
const filterItemSelectData = () => {
  let filtered = allItemSelectData
  if (activeItemType.value !== '全部') {
    filtered = allItemSelectData.filter(item => item.itemType === activeItemType.value)
  }
  itemSelectPage.total = filtered.length
  const start = (itemSelectPage.PageIndex - 1) * itemSelectPage.pageSize
  const end = start + itemSelectPage.pageSize
  itemSelectTableData.value = filtered.slice(start, end)
}
const handleItemTypeClick = (type: string) => {
  activeItemType.value = type
  itemSelectPage.PageIndex = 1
  filterItemSelectData()
}
const handleRadioChange = (row: { itemCode: string; itemName: string }) => {
  itemSelectRadio.value = row.itemCode
  selectedItemRow.value = row
}
const handleRadioChangeWithEvent = (row: { itemCode: string; itemName: string }, _event: any) => {
  handleRadioChange(row);
}
const getItemTableData = () => {
  if (!formInline.PlanNo) return
  http.get('/api/Testingitems/GetList/GetTestingitems?PlanNo=' + formInline.PlanNo, {
    params: {
      PageIndex: itemPage.PageIndex,
      PageSize: itemPage.pageSize
    }
  }).then(res => {
    itemTableData.value = res.rows || []
    itemPage.total = res.total || 0
  })
}
const openProductSelectDialog = () => {
  productSelectDialogVisible.value = true
}
const onProductSelectConfirm = () => {
  // 这里后续实现选中物料后赋值逻辑
  productSelectDialogVisible.value = false
}
const getProductTableData = () => {
  if (!formInline.PlanNo) return
  http.get('/api/ProductInspectionTemplate/GetProductInspectionTemplate?PlanNo=' + formInline.PlanNo + '&pageIndex=' + productPage.PageIndex + '&pageSize=' + productPage.pageSize)
    .then(res => {
      productTableData.value = res.rows || []
      productPage.total = res.total || 0
    })
}
const onEditProductSelected = () => {
  if (selectedProductRows.value.length !== 1) {
    ElMessage.warning('请选择一条产品进行修改')
    return
  }
  onEditProduct(selectedProductRows.value[0])
}
watch(activeTab, (val) => {
  if (dialogVisible.value && val === 'product') {
    getProductTableData()
  }
})
onMounted(() => {
  getTableData()
})
defineExpose({ handleRadioChangeWithEvent });
</script>
<style lang="scss" scoped>
.tooling-ledger-container {
  padding: 15px;
  background: #f6f8fa;
  position: relative;

  .search-form {
    background: #fff;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 15px;

    .el-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
        
        :deep(.el-form-item__content) {
          margin-left: 0 !important;
        }

        :deep(.el-input) {
          width: 200px;
        }

        :deep(.el-select) {
          width: 200px;
        }
      }
    }
  }

  .table-operations {
    margin-bottom: 15px;
    display: flex;
    gap: 10px;

    .el-button {
      .el-icon {
        margin-right: 4px;
      }

      &:disabled {
        cursor: not-allowed;
        opacity: 0.7;
      }
    }
  }

  .table-wrapper {
    background: #fff;
    padding: 15px;
    border-radius: 4px;
    position: static;
    
    .ledger-table {
      // 设置表格边框和圆角
      :deep(.el-table__inner-wrapper) {
        border-radius: 4px;
        overflow: hidden;
      }

      // 设置表格hover效果
      :deep(.el-table__row:hover) {
        td {
          background-color: #f5f7fa !important;
        }
      }

      // 设置斑马纹颜色
      :deep(.el-table__row--striped) {
        td {
          background-color: #fafafa;
        }
      }

      // 设置操作列样式
      :deep(.operation-link) {
        font-size: 13px;
        
        & + .el-divider {
          margin: 0 8px;
        }
      }

      // 设置链接列样式
      :deep(.el-link) {
        font-size: 13px;
      }

      // 设置状态标签样式
      :deep(.el-tag) {
        border-radius: 2px;
      }
    }

    .table-header-actions-flex {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-bottom: 4px;
    }
    .table-header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .full-width-table .el-table {
    width: 100% !important;
    min-width: 0 !important;
  }

  .ledger-table ::v-deep .el-table__header th {
    font-weight: bold;
    background: #f4f6fa;
  }

  .filter-btns {
    text-align: right;
  }

  .pager-wrapper {
    margin-top: 15px;
    padding: 0 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    :deep(.el-pagination) {
      padding: 0;
      margin: 0;
      font-weight: normal;
      
      .el-pagination__total {
        margin-right: 16px;
      }
      
      .el-pagination__sizes {
        margin-right: 16px;
      }
    }
  }

  .tooling-dialog {
    :deep(.el-dialog__body) {
      padding: 15px 25px;
    }

    .tooling-form {
      .form-section {
        margin-bottom: 15px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }

      .form-section-row {
        display: flex;
        gap: 20px;
        margin-bottom: 15px;

        .form-section-col {
          flex: 1;
        }
      }

      .section-title {
        font-size: 14px;
        font-weight: 500;
        color: #1f2f3d;
        margin-bottom: 12px;
        padding-left: 8px;
        border-left: 3px solid #409eff;
      }

      .section-content {
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 4px;

        .el-row {
          margin-bottom: 15px;
          
          &:last-child {
            margin-bottom: 0;
          }
        }

        .el-form-item {
          margin-bottom: 15px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }

      :deep(.el-form-item) {
        margin-bottom: 0;
        
        .el-form-item__label {
          font-weight: normal;
          color: #606266;
          padding-right: 8px;
          line-height: 32px;
        }
        
        .el-form-item__content {
          line-height: 32px;

          .el-input,
          .el-select,
          .el-date-picker,
          .el-input-number {
            width: 100%;
          }
        }

        .status-group {
          display: flex !important;
          flex-wrap: nowrap !important;
          gap: 15px;
          justify-content: flex-start;

          .el-radio {
            margin-right: 0;
            margin-left: 0;
          }
        }

        .el-input-group__append {
          padding: 0 10px;
          background-color: var(--el-fill-color-blank);

          .el-switch {
            --el-switch-on-color: var(--el-color-primary);
            height: 28px;
            line-height: 28px;
          }
        }
      }

      .full-width {
        width: 100%;
      }
    }

    .dialog-footer {
      padding-top: 15px;
      text-align: right;
      border-top: 1px solid #dcdfe6;
      
      .el-button + .el-button {
        margin-left: 12px;
      }
    }

    :deep(.el-switch) {
      margin-right: 8px;
      
      &.is-disabled {
        opacity: 0.7;
      }
    }
  }

  .product-dialog :deep(.el-dialog__body) {
    padding-left: 40px;
    padding-right: 40px;
  }

  .product-table {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
    overflow: hidden;
    th {
      background: #f4f6fa !important;
      font-weight: bold !important;
      color: #2c3e50 !important;
      text-align: center !important;
      font-size: 16px;
    }
    td {
      text-align: center !important;
      font-size: 15px;
      color: #444;
    }
    .el-table__body tr:hover>td {
      background: #f0f7ff !important;
    }
    .el-table__row--striped td {
      background: #fafbfc;
    }
    .el-table__empty-block {
      min-height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      color: #bbb;
    }
  }
}
</style>